import React, { useEffect, useState } from "react";
import { InputItem, Button, WhiteSpace, Toast } from "antd-mobile";
import axios from "axios";

import "./index.css";

const Login = ({ match, history, location }) => {
    // 用户名
    const [username, setUsername] = useState("");

    // 密码
    const [password, setPassword] = useState("");

    const onLoginClicked = async () => {
        if (!username || !password) {
            Toast.fail("用户名或密码不能为空");
            return;
        }

        const res = await axios.post("/login", { username, password });

        if (res.data.code !== 200) {
            Toast.fail(res.data.message);
            return;
        }

        // 保存用户登录态
        window.sessionStorage.setItem(
            "user",
            JSON.stringify(res.data.data.user)
        );
        // 保存 token
        window.sessionStorage.setItem("token", res.data.data.token);

        // 登录成功，跳转到地址管理页面
        history.push("/address/list");
    };

    return (
        <div className="login">
            <div className="login-box">
                <h2>登录</h2>

                <InputItem
                    placeholder="请输入用户名"
                    onChange={(val) => setUsername(val)}
                />

                <WhiteSpace size="lg" />

                <InputItem
                    placeholder="请输入密码"
                    onChange={(val) => setPassword(val)}
                />

                <WhiteSpace size="lg" />

                <Button type="primary" onClick={onLoginClicked}>
                    登录
                </Button>
            </div>
        </div>
    );
};

export default Login;
